package buco.core.internal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;

import buco.dsl.BclParser;
import buco.dsl.BclConstraint;

/***
 * This filter reads the BCL code from a bundle and parses it.
 *  
 * @author Christopher
 *
 */
public class BclFilter implements Filter<ProcessJarContext> {

	@Override
	public ProcessJarContext process(ProcessJarContext ctx) {
		try {
			JarEntry bclEntry = null; 
			Enumeration<JarEntry> enumerator = ctx.getJarFile().entries();
			while(enumerator.hasMoreElements()) {
				JarEntry entry = enumerator.nextElement(); 
				if(entry.getName().endsWith(".bcl")) {
					bclEntry = entry; 
					break;
				}
			}
			
			if(bclEntry != null) { 			
				InputStream is = ctx.getJarFile().getInputStream(bclEntry);
				InputStreamReader sr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(sr);
				StringBuilder sb = new StringBuilder(); 
				String line = null; 
				while((line = br.readLine()) != null) { 
					sb.append(line + "\n");
				}
				is.close();
				
				ctx.getBundle().setBcl(sb.toString()); 
				
				// Parse file
				BclParser parser = new BclParser(); 
				List<BclConstraint> commands = parser.parse(ctx.getBundle().getBcl());
				if(commands != null) {			
					// Copy constraints
					for(BclConstraint command : commands) { 
						ctx.getBundle().addSemanticConstraint(command.getIdentifier(), command.getObject());
					}
				}
			}
			
		} catch (IOException e) {			
			e.printStackTrace();
		}		
		return ctx;
	}

}
